import { useContext, useRef, useEffect, useState } from 'react'
import { EditorConfigContext } from '../App'

function EditorBlock(props) {
  const ref = useRef(null)
  const { componentMap } = useContext(EditorConfigContext)
  const { block } = props
  const [blockStyles, setBlockStyles] = useState({
    top: block.top,
    left: block.left,
    zIndex: block.zIndex,
  })

  useEffect(() => {
    if (block.alignCenter) {
      const element = ref.current
      const { offsetWidth, offsetHeight } = element
      if (element) {
        setBlockStyles({
          ...blockStyles,
          top: blockStyles.top - offsetHeight / 2,
          left: blockStyles.left - offsetWidth / 2,
          alignCenter: false,
        })
      }
    }
  }, [block])

  const nodeComponent = componentMap[block.key].render()

  return (
    <div className="editor-block" style={blockStyles} ref={ref} draggable>
      {nodeComponent}
    </div>
  )
}

export default EditorBlock
